package server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author oyz
 * 依赖输出流来封装response
 * 提供核心方法,输出html
 */
public class Response {

    private OutputStream outputStream;

    public Response(){

    }


    public Response(OutputStream outputStream){
        this.outputStream = outputStream;
    }

    /**
     * 使用输出流来输出指定字符串
     */
    public void outPut(String context) throws IOException {
        outputStream.write(context.getBytes());
    }

    /**
     * 根据url获取静态资源的绝对路径，进一步根据绝对路径获取到静态资源文件，最终通过输出流来进行输出
     * @param path
     */
    public void outputHtml(String path) throws IOException {
        // 获取静态资源的绝对路径
        String absoluteResourcePath = StaticResourceUtil.getAbsolutePath(path);
        // 输入静态资源文件
        File file = new File(absoluteResourcePath);
        if (file.exists()&&file.isFile()){
            // 读取静态资源文件,输出静态资源
            StaticResourceUtil.outputStaticResource(new FileInputStream(file),outputStream);

        }else{
            // 输出404
            outPut(HttpProtocolUtil.getHttpHeader404());
        }
    }




}

